package com.ruoyi.mdm.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mdm.domain.*;
import com.ruoyi.mdm.mapper.*;
import com.ruoyi.mdm.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * sku主档Service业务层处理
 *
 * @author shiseido
 * @date 2025-03-01
 */
@Service
@Slf4j
public class SkuMasterServiceImpl implements ISkuMasterService {
    @Autowired
    private SkuMasterMapper skuMasterMapper;

    @Autowired
    private SkuMasterSubMapper skuMasterSubMapper;

    @Autowired
    private SkuMergeMasterMapper skuMergeMasterMapper;

    @Autowired
    private SkuMergeMasterSubMapper skuMergeMasterSubMapper;


    @Autowired
    private SkuProductMasterMapper skuProductMasterMapper;

    @Autowired
    private SkuProductMasterSubMapper skuProductMasterSubMapper;

    @Autowired
    private ISkuInfoService skuInfoService;

    @Autowired
    private ISkuMergeMasterService skuMergeMasterService;

    @Autowired
    private ISkuMetricsScoreService skuMetricsScoreService;

    @Autowired
    private SkuSampleMapper skuSampleMapper;

    /**
     * 查询sku主档
     *
     * @param id sku主档主键
     * @return sku主档
     */
    @Override
    public SkuMaster selectSkuMasterById(Long id) {
        return skuMasterMapper.selectSkuMasterById(id);
    }

    /**
     * 查询sku主档列表
     *
     * @param skumCode skum编码
     * @return sku主档
     */
    @Override
    public List<SkuMaster> selectSkuMasterBySkumCode(String skumCode) {
        return skuMasterMapper.selectSkuMasterBySkumCode(skumCode);
    }


    /**
     * 查询sku主档列表
     *
     * @param spuCode spu编码
     * @return sku主档
     */
    @Override
    public List<SkuMaster> selectSkuMasterBySpuCode(String spuCode) {
        return skuMasterMapper.selectSkuMasterBySpuCode(spuCode);
    }

    /**
     * 查询sku主档列表
     *
     * @param skuMaster sku主档
     * @return sku主档集合
     */
    @Override
    public List<SkuMaster> selectSkuMasterList(SkuMaster skuMaster) {
        return skuMasterMapper.selectSkuMasterList(skuMaster);
    }

    /**
     * 新增sku主档
     *
     * @param skuMaster sku主档
     * @return 结果
     */
    @Override
    public int insertSkuMaster(SkuMaster skuMaster) {
        skuMaster.setCreateTime(DateUtils.getNowDate());
        return skuMasterMapper.insertSkuMaster(skuMaster);
    }

    /**
     * 修改sku主档
     *
     * @param skuMaster sku主档
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSkuMaster(SkuMaster skuMaster) {

        // 更新子对象
        SkuMasterSub skuMasterSub = skuMasterSubMapper.selectSkuMasterSubBySkuCode(
                skuMaster.getOwnerId(), skuMaster.getGoodsCode());
        if (skuMasterSub == null) {
            skuMasterSub = new SkuMasterSub();
            skuMasterSub.setOwnerId(skuMaster.getOwnerId());
            skuMasterSub.setSkuCode(skuMaster.getGoodsCode());
            skuMasterSub.setSkuRecommendFlag(skuMaster.getSkuRecommendFlag());
            skuMasterSub.setSkuSalesChannel(skuMaster.getSkuSalesChannel());
            skuMasterSub.setContent(skuMaster.getContent());
            skuMasterSub.setContentUnit(skuMaster.getContentUnit());
            skuMasterSub.setNetcontent(skuMaster.getNetcontent());
            skuMasterSub.setCreateBy(skuMaster.getCreateBy());
            skuMasterSub.setUpdateBy(skuMaster.getUpdateBy());
            skuMasterSub.setCreateTime(DateUtils.getNowDate());
            skuMasterSub.setUpdateTime(DateUtils.getNowDate());
            skuMasterSubMapper.insertSkuMasterSub(skuMasterSub);

        } else {
            skuMasterSub.setSkuRecommendFlag(skuMaster.getSkuRecommendFlag());
            skuMasterSub.setSkuSalesChannel(skuMaster.getSkuSalesChannel());
            skuMasterSub.setContent(skuMaster.getContent());
            skuMasterSub.setContentUnit(skuMaster.getContentUnit());
            skuMasterSub.setNetcontent(skuMaster.getNetcontent());
            skuMasterSub.setUpdateBy(skuMaster.getUpdateBy());
            skuMasterSub.setUpdateTime(DateUtils.getNowDate());
            skuMasterSubMapper.updateSkuMasterSub(skuMasterSub);

        }

        // SKUM关联查询
        SkuMergeMasterSub skuMergeMasterSub = skuMergeMasterSubMapper.selectSkuMergeMasterSubBySkuCode(
                skuMaster.getOwnerId(), skuMaster.getGoodsCode());

        // 原先关联SKUM编码
        String oldSkumCode = null;

        // 如果存在删除，再新增关联
        if (skuMergeMasterSub != null) {
            skuMergeMasterSubMapper.deleteSkuMergeMasterSubById(skuMergeMasterSub.getId());
            oldSkumCode = skuMergeMasterSub.getSkumCode();
        }

        Long newSkumId = null;
        if (StringUtils.isNotEmpty(skuMaster.getSkumCode())) {
            skuMergeMasterSub = new SkuMergeMasterSub();
            skuMergeMasterSub.setOwnerId(skuMaster.getOwnerId());
            skuMergeMasterSub.setSkuCode(skuMaster.getGoodsCode());
            skuMergeMasterSub.setSkuName(skuMaster.getGoodsName());
            skuMergeMasterSub.setSkumId(skuMaster.getSkumId());
            skuMergeMasterSub.setSkumCode(skuMaster.getSkumCode());
            skuMergeMasterSub.setCreateBy(skuMaster.getCreateBy());
            skuMergeMasterSub.setUpdateBy(skuMaster.getUpdateBy());
            skuMergeMasterSub.setCreateTime(DateUtils.getNowDate());
            skuMergeMasterSub.setUpdateTime(DateUtils.getNowDate());
            skuMergeMasterSubMapper.insertSkuMergeMasterSub(skuMergeMasterSub);

        }

        // SPU关联查询
        SkuProductMasterSub skuProductMasterSub = null;

        if (StringUtils.isNotEmpty(oldSkumCode)) {
            skuProductMasterSub = skuProductMasterSubMapper.selectSkuProductMasterSubBySkumCode(
                    oldSkumCode);
            // 如果存在删除，再新增关联
            if (skuProductMasterSub != null) {
                skuProductMasterSubMapper.deleteSkuProductMasterSubById(skuProductMasterSub.getId());
            }
        }

        if (StringUtils.isNotEmpty(skuMaster.getSpuCode())) {

            SkuProductMasterSub skuProductMasterSubCheck = new SkuProductMasterSub();
            skuProductMasterSubCheck.setSkumCode(skuMaster.getSkumCode());
            skuProductMasterSubCheck.setSpuCode(skuMaster.getSpuCode());
            List<SkuProductMasterSub> skuProductMasterSubCheckList
                    = skuProductMasterSubMapper.selectSkuProductMasterSubList(skuProductMasterSubCheck);
            if (StringUtils.isEmpty(skuProductMasterSubCheckList)) {
                skuProductMasterSub = new SkuProductMasterSub();
                skuProductMasterSub.setOwnerId(skuMaster.getOwnerId());
                skuProductMasterSub.setSkumId(skuMaster.getSkumId());
                skuProductMasterSub.setSkumCode(skuMaster.getSkumCode());
//                skuProductMasterSub.setSpuId(skuMaster.getSpuId());
                skuProductMasterSub.setSpuCode(skuMaster.getSpuCode());
                skuProductMasterSub.setCreateBy(skuMaster.getCreateBy());
                skuProductMasterSub.setUpdateBy(skuMaster.getUpdateBy());
                skuProductMasterSub.setCreateTime(DateUtils.getNowDate());
                skuProductMasterSub.setUpdateTime(DateUtils.getNowDate());
                skuProductMasterSubMapper.insertSkuProductMasterSub(skuProductMasterSub);
            }
        }

        skuMaster.setCreateTime(DateUtils.getNowDate());
        skuMaster.setUpdateTime(DateUtils.getNowDate());
        skuMasterMapper.updateSkuMaster(skuMaster);

        // 计算单独某个产品指标得分
        skuMetricsScoreService.calculateSkuCodeMetricsScore(
                skuMaster.getOwnerId(), skuMaster.getGoodsCode());

        // 同步SKU TO ES 异步处理
        syncSkuToEs(skuMaster.getId(), newSkumId);

        return 1;
    }

    @Async
    public void syncSkuToEs(Long skuId, Long skumId) {
        SkuMaster skuSelectMaster = new SkuMaster();
        skuSelectMaster.setId(skuId);
        List<SkuMaster> skuMasterList = skuMasterMapper.selectSkuMasterToEs(skuSelectMaster);
        if(!skuMasterList.isEmpty()){
            syncSkuToEs(skuMasterList, false);
        }

        // 由于SKUM 销售价格可能有变化 也需要同步
        if (skumId != null) {
            SkuMergeMaster skuMergeMaster = skuMergeMasterMapper.selectSkuMergeMasterById(skumId);
            if(null != skuMergeMaster){
                skuMergeMasterService.syncSkumToEs(skuMergeMaster);
            }

        }
    }

    /**
     * 批量删除sku主档
     *
     * @param ids 需要删除的sku主档主键
     * @return 结果
     */
    @Override
    public int deleteSkuMasterByIds(Long[] ids) {
        return skuMasterMapper.deleteSkuMasterByIds(ids);
    }

    /**
     * 删除sku主档信息
     *
     * @param id sku主档主键
     * @return 结果
     */
    @Override
    public int deleteSkuMasterById(Long id) {
        return skuMasterMapper.deleteSkuMasterById(id);
    }

    /**
     * 同步SKU到ES
     *
     * @param skuMasterList spu信息
     */
    @Override
    public void syncSkuToEs(List<SkuMaster> skuMasterList, boolean delAllFlag) {

        List<SkuInfoEntity> skuInfoEntityList = new ArrayList<>();

        for (SkuMaster skuMaster : skuMasterList) {

            // 同步更新ES-SKU
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(skuMaster, skuInfoEntity);
            // 日期转换
            skuInfoEntity.setSaleBeginDate(DateUtils.parseDateToTStr(skuMaster.getSaleBeginDate()));
            skuInfoEntity.setSaleEndDate(DateUtils.parseDateToTStr(skuMaster.getSaleEndDate()));
            skuInfoEntity.setUpdateDate(DateUtils.parseDateToTStr(skuMaster.getUpdateDate()));
            skuInfoEntity.setTransferDate(DateUtils.parseDateToTStr(skuMaster.getTransferDate()));
            skuInfoEntity.setEtlInsertTime(DateUtils.parseDateToTStr(skuMaster.getEtlInsertTime()));
            skuInfoEntity.setBizDate(DateUtils.parseDateToTStr(skuMaster.getBizDate()));
            skuInfoEntity.setSnycDate(DateUtils.parseDateToTStr(skuMaster.getSnycDate()));

            // id设定
            skuInfoEntity.setId(skuMaster.getChannelCode() + "_" + skuMaster.getOwnerId() + "_" + skuMaster.getGoodsCode());

            // skuId设定
            skuInfoEntity.setSkuId(skuMaster.getId());

            // 品牌名称
            String goodsBrandName = DictUtils.getDictLabel("goods_brand", skuMaster.getOwnerId());
            skuInfoEntity.setOwnerName(goodsBrandName);

            StringBuffer keyword = new StringBuffer();
            keyword = keyword.append(skuMaster.getOwnerId()).append(" ");
            keyword = keyword.append(goodsBrandName).append(" ");
//            keyword = keyword.append(skuMaster.getGoodsCode()).append(" ");
            keyword = keyword.append(skuMaster.getGoodsName()).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getGoodsNameEn(),"")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getGoodsShortName(),"")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getSkumName(),"")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getSkumNameEn(),"")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getSkumShortName(),"")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getSpuName(), "")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getSpuNameEn(),"")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getSpuShortName(), "")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getSpuNickName(), "")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getContent(), "")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getContentUnit(), "")).append(" ");
            keyword = keyword.append(StringUtils.nvl(skuMaster.getNetcontent(), "")).append(" ");
//            keyword = keyword.append(skuMaster.getBarCode());
            skuInfoEntity.setKeyword(keyword.toString());

            skuInfoEntityList.add(skuInfoEntity);
        }

        if (delAllFlag) {
            skuInfoService.deleteAll();
        }
        skuInfoService.addAll(skuInfoEntityList);
    }

    /**
     * 导入产品
     *
     * @param skuMasterSubImportList         推荐渠道数据列表
     * @param operName                  操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public List<Map> importSkuMasterSub(List<SkuMasterSubImport> skuMasterSubImportList,
                                        List<SkuMergeMasterSubImport> spuContentList,
                                        String operName) {
        List<Map> messageList = new ArrayList<>();
        Map<String, String> messageMap = new HashMap<>();

        List<SkuMasterSub> skuMasterSubList = new ArrayList<>();

        // 渠道和推荐品导入处理
        int index = 1;
        String sheetName1 = "渠道和推荐品";
        for (SkuMasterSubImport skuMasterSubImport : skuMasterSubImportList) {
            index = index + 1;

            SkuMasterSub skuMasterSub = new SkuMasterSub();

            // 产品编码必填
            if (StringUtils.isEmpty(skuMasterSubImport.getGoodsCode())) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName1);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "产品编码必填！");
                messageList.add(messageMap);
                continue;
            }

            // 品牌必填
            if (StringUtils.isEmpty(skuMasterSubImport.getBrandName())) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName1);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "品牌必填！");
                messageList.add(messageMap);
                continue;
            }

            String ownerId = DictUtils.getDictValue("goods_brand", skuMasterSubImport.getBrandName());
            if (StringUtils.isEmpty(ownerId)) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName1);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "品牌:【" + skuMasterSubImport.getBrandName() + "】在数据字典中不存在！");
                messageList.add(messageMap);
                continue;
            }

            SkuMaster skuMaster = skuMasterMapper.selectSkuMasterByGoodsCode(
                    ownerId, skuMasterSubImport.getGoodsCode());
            if (skuMaster == null) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName1);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "产品编码:【" + skuMasterSubImport.getGoodsCode() + "】不存在！");
                messageList.add(messageMap);
                continue;
            }

            // 产品ID
            skuMasterSub.setSkuId(skuMaster.getId());

            // 品牌代码
            skuMasterSub.setOwnerId(ownerId);

            // 产品编码
            skuMasterSub.setSkuCode(skuMaster.getGoodsCode());
            // 是否推荐
            String importRecommendFlag = null;
            if ("是".equals(skuMasterSubImport.getSkuRecommendFlag())) {
                importRecommendFlag = "Y";
            } else if ("否".equals(skuMasterSubImport.getSkuRecommendFlag())) {
                importRecommendFlag = "N";
            }
            if (importRecommendFlag == null) {
                importRecommendFlag = skuMaster.getSkuRecommendFlag();
            }
            skuMasterSub.setSkuRecommendFlag(importRecommendFlag);

            // 销售渠道
            List<String> salesChannelList = new ArrayList<>();
            if ("是".equals(skuMasterSubImport.getPosSalesChannel())) {
                salesChannelList.add("POS");
            }
            if ("是".equals(skuMasterSubImport.getTmSalesChannel())) {
                salesChannelList.add("TM");
            }
            if ("是".equals(skuMasterSubImport.getJdSalesChannel())) {
                salesChannelList.add("JD");
            }
            if ("是".equals(skuMasterSubImport.getDySalesChannel())) {
                salesChannelList.add("DY");
            }
            if ("是".equals(skuMasterSubImport.getDtcSalesChannel())) {
                salesChannelList.add("DTC");
            }
            if ("是".equals(skuMasterSubImport.getSflSalesChannel())) {
                salesChannelList.add("SFL");
            }
            if (StringUtils.isNotEmpty(skuMaster.getSkuSalesChannel())) {
                StringTokenizer tokenizer = new StringTokenizer(skuMaster.getSkuSalesChannel(), ",");
                while(tokenizer.hasMoreTokens()) {
                    salesChannelList.add(tokenizer.nextToken());
                }
            }

            // 去重
            salesChannelList = salesChannelList.stream().distinct().collect(Collectors.toList());

            // 把 “否” 去掉
            if ("否".equals(skuMasterSubImport.getPosSalesChannel())) {
                salesChannelList.remove("POS");
            }
            if ("否".equals(skuMasterSubImport.getTmSalesChannel())) {
                salesChannelList.remove("TM");
            }
            if ("否".equals(skuMasterSubImport.getJdSalesChannel())) {
                salesChannelList.remove("JD");
            }
            if ("否".equals(skuMasterSubImport.getDySalesChannel())) {
                salesChannelList.remove("DY");
            }
            if ("否".equals(skuMasterSubImport.getDtcSalesChannel())) {
                salesChannelList.remove("DTC");
            }
            if ("否".equals(skuMasterSubImport.getSflSalesChannel())) {
                salesChannelList.remove("SFL");
            }
            // 转逗号分隔保存
            skuMasterSub.setSkuSalesChannel(salesChannelList.stream().collect(Collectors.joining(",")));

            skuMasterSubList.add(skuMasterSub);

        }

        List<SkuMergeMasterSub> skuMergeMasterSubList = new ArrayList<>();
        List<SkuProductMasterSub> skuProductMasterSubDataList = new ArrayList<>();
        index = 1;
        String sheetName3 = "产品容量和关联SPU";
        for (SkuMergeMasterSubImport skuMergeMasterSubImport : spuContentList) {
            index = index + 1;

            // 产品编码必填
            if (StringUtils.isEmpty(skuMergeMasterSubImport.getGoodsCode())) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName3);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "产品编码必填！");
                messageList.add(messageMap);
                continue;
            }

            // 品牌必填
            if (StringUtils.isEmpty(skuMergeMasterSubImport.getBrandName())) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName3);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "品牌必填！");
                messageList.add(messageMap);
                continue;
            }

            // 合法性检查
            String ownerId = DictUtils.getDictValue("goods_brand", skuMergeMasterSubImport.getBrandName());
            if (StringUtils.isEmpty(ownerId)) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName3);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "品牌:【" + skuMergeMasterSubImport.getBrandName() + "】在数据字典中不存在！");
                messageList.add(messageMap);
                continue;
            }

            // SKUM中文名称必填
            if (StringUtils.isEmpty(skuMergeMasterSubImport.getSkumName())) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName3);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "SKUM中文名称必填！");
                messageList.add(messageMap);
                continue;
            }

            // 合法性检查
            SkuMaster skuMaster = new SkuMaster();
            skuMaster.setGoodsCode(skuMergeMasterSubImport.getGoodsCode());
            skuMaster.setOwnerId(ownerId);
            List<SkuMaster> skuMasterList = skuMasterMapper.selectSkuMasterList(skuMaster);
            if (StringUtils.isEmpty(skuMasterList)) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName3);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "品牌:【" + skuMergeMasterSubImport.getBrandName()
                        + "】产品编码:【" + skuMergeMasterSubImport.getGoodsCode() + "】不存在！");
                messageList.add(messageMap);
                continue;
            }
            skuMaster = skuMasterList.get(0);

            SkuMergeMaster skuMergeMasterParam = new SkuMergeMaster();
            skuMergeMasterParam.setOwnerId(ownerId);
            skuMergeMasterParam.setSkumName(skuMergeMasterSubImport.getSkumName());
            List<SkuMergeMaster> skuMergeMasterList = skuMergeMasterMapper.selectSkuMergeMasterList(skuMergeMasterParam);
            if (StringUtils.isEmpty(skuMergeMasterList)) {
                messageMap = new HashMap<>();
                messageMap.put("sheetName", sheetName3);
                messageMap.put("index", String.valueOf(index));
                messageMap.put("message", "品牌:【" + skuMergeMasterSubImport.getBrandName()
                        + "】SKUM中文名称:【" + skuMergeMasterSubImport.getSkumName() + "】不存在！");
                messageList.add(messageMap);
                continue;
            }
            SkuMergeMaster skuMergeMaster = skuMergeMasterList.get(0);

            SkuMergeMasterSub skuMergeMasterSub = new SkuMergeMasterSub();
            skuMergeMasterSub.setOwnerId(ownerId);
            skuMergeMasterSub.setSkuCode(skuMergeMasterSubImport.getGoodsCode());
            skuMergeMasterSub.setSkuId(skuMaster.getId());
            skuMergeMasterSub.setSkumId(skuMergeMaster.getId());
            skuMergeMasterSub.setSkumCode(skuMergeMaster.getSkumCode());
            skuMergeMasterSubList.add(skuMergeMasterSub);

            // sku_master_sub  更新 容量
            {
                // 容量校验
                if (StringUtils.isEmpty(skuMergeMasterSubImport.getSkumNetWeight()) ||  !isPositiveNumber(skuMergeMasterSubImport.getSkumNetWeight())){
                    messageMap = new HashMap<>();
                    messageMap.put("sheetName", sheetName3);
                    messageMap.put("index", String.valueOf(index));
                    messageMap.put("message", "容量="+skuMergeMasterSubImport.getSkumNetWeight()+"设置异常！");
                    messageList.add(messageMap);
                    continue;
                }

                // 容量单位
                if (StringUtils.isEmpty(skuMergeMasterSubImport.getSkumNetWeightUnit())) {
                    messageMap = new HashMap<>();
                    messageMap.put("sheetName", sheetName3);
                    messageMap.put("index", String.valueOf(index));
                    messageMap.put("message", "容量单位必填！");
                    messageList.add(messageMap);
                    continue;
                }

                // 容量单位 校验
                if (!skuMergeMasterSubImport.getSkumNetWeightUnit().equalsIgnoreCase("ml") &&
                        !skuMergeMasterSubImport.getSkumNetWeightUnit().equalsIgnoreCase("g") &&
                        !skuMergeMasterSubImport.getSkumNetWeightUnit().equalsIgnoreCase("pc")
                ) {
                    messageMap = new HashMap<>();
                    messageMap.put("sheetName", sheetName3);
                    messageMap.put("index", String.valueOf(index));
                    messageMap.put("message", "容量单位错误！ 正确的是：ml/g/pc");
                    messageList.add(messageMap);
                    continue;
                }

                // 更新子对象
                SkuMasterSub skuMasterSub = skuMasterSubMapper.selectSkuMasterSubBySkuCode(
                        skuMaster.getOwnerId(), skuMaster.getGoodsCode());
                if (skuMasterSub == null) {
                    skuMasterSub = new SkuMasterSub();
                    skuMasterSub.setOwnerId(skuMaster.getOwnerId());
                    skuMasterSub.setSkuCode(skuMaster.getGoodsCode());
                    skuMasterSub.setContent(skuMergeMasterSubImport.getSkumNetWeight());
                    skuMasterSub.setContentUnit(skuMergeMasterSubImport.getSkumNetWeightUnit());
                    skuMasterSub.setCreateBy(operName);
                    skuMasterSub.setUpdateBy(operName);
                    skuMasterSub.setCreateTime(DateUtils.getNowDate());
                    skuMasterSub.setUpdateTime(DateUtils.getNowDate());
                    skuMasterSubMapper.insertSkuMasterSub(skuMasterSub);
                } else {
                    SkuMasterSub skumastersub = new SkuMasterSub();
                    skumastersub.setOwnerId(ownerId);
                    skumastersub.setSkuCode(skuMergeMasterSubImport.getGoodsCode());
                    skumastersub.setContent(skuMergeMasterSubImport.getSkumNetWeight());
                    skumastersub.setContentUnit(skuMergeMasterSubImport.getSkumNetWeightUnit());
                    skumastersub.setUpdateBy(operName);
                    skumastersub.setUpdateTime(DateUtils.getNowDate());
                    skuMasterSubMapper.updateSkuMasterSub(skumastersub);
                }

                //更新skum
                skuMergeMaster.setSkumNetWeight(skuMergeMasterSubImport.getSkumNetWeight());
                skuMergeMaster.setSkumNetWeightUnit(skuMergeMasterSubImport.getSkumNetWeightUnit());
                skuMergeMasterMapper.updateSkuMergeMaster(skuMergeMaster);
            }

            // sku_product_master_sub 更新
            {
                if (StringUtils.isEmpty(skuMergeMasterSubImport.getSpuName())) {
                    messageMap = new HashMap<>();
                    messageMap.put("sheetName", sheetName1);
                    messageMap.put("index", String.valueOf(index));
                    messageMap.put("message", "spu 名称设置异常！");
                    messageList.add(messageMap);
                    continue;
                }
                SkuProductMaster skuProductMaster = new SkuProductMaster();
                skuProductMaster.setOwnerId(ownerId);
                skuProductMaster.setSpuName(skuMergeMasterSubImport.getSpuName());
//                skuProductMaster.setSearchSpuName(skuMergeMasterSubImport.getSpuName());
                List<SkuProductMaster> skuProductMasterList = skuProductMasterMapper.selectSkuProductMasterList(skuProductMaster);
                if (StringUtils.isEmpty(skuProductMasterList)) {
                    messageMap = new HashMap<>();
                    messageMap.put("sheetName", sheetName3);
                    messageMap.put("index", String.valueOf(index));
                    messageMap.put("message", "品牌:【" + skuMergeMasterSubImport.getBrandName()
                            + "】SPU中文名称:【" + skuMergeMasterSubImport.getSpuName() + "】不存在！");
                    messageList.add(messageMap);
                    continue;
                }
                SkuProductMaster retSkuProductMaster = skuProductMasterList.get(0);

                SkuProductMasterSub skuProductMasterSub = new SkuProductMasterSub();
                skuProductMasterSub.setOwnerId(ownerId);
//                skuProductMasterSub.setSpuId(retSkuProductMaster.getId());
                skuProductMasterSub.setSpuCode(retSkuProductMaster.getSpuCode());
                skuProductMasterSub.setSkumId(skuMergeMaster.getId());
                skuProductMasterSub.setSkumCode(skuMergeMaster.getSkumCode());

                skuProductMasterSubDataList.add(skuProductMasterSub);
            }

        }

        if (messageList != null && messageList.size() > 0) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String json = objectMapper.writeValueAsString(messageList);
                throw new ServiceException(json);
            } catch (JsonProcessingException e) {
            }
        }

        // 渠道和推荐品 处理
        importSkuMasterSubList(skuMasterSubList, operName);

        // 导入 产品容量和关联SPU
        importSkuProductMasterSubList(skuMergeMasterSubList, skuProductMasterSubDataList, operName);


        // 同步SKU SKUM 到ES 异步处理
        importSyncSkuToEs(skuMasterSubList, skuMergeMasterSubList);

        return null;
    }

    /**
     * 导入 渠道和推荐品
     */
    private void importSkuMasterSubList(List<SkuMasterSub> skuMasterSubList, String operName) {

        for (SkuMasterSub skuMasterSub : skuMasterSubList) {
            // 更新子对象
            SkuMasterSub skuMasterSubOld = skuMasterSubMapper.selectSkuMasterSubBySkuCode(
                    skuMasterSub.getOwnerId(), skuMasterSub.getSkuCode());
            if (skuMasterSubOld == null) {
                skuMasterSubOld = new SkuMasterSub();
                skuMasterSubOld.setOwnerId(skuMasterSub.getOwnerId());
                skuMasterSubOld.setSkuCode(skuMasterSub.getSkuCode());
                skuMasterSubOld.setSkuRecommendFlag(skuMasterSub.getSkuRecommendFlag());
                skuMasterSubOld.setSkuSalesChannel(skuMasterSub.getSkuSalesChannel());
                skuMasterSubOld.setCreateBy(operName);
                skuMasterSubOld.setUpdateBy(operName);
                skuMasterSubOld.setCreateTime(DateUtils.getNowDate());
                skuMasterSubOld.setUpdateTime(DateUtils.getNowDate());
                skuMasterSubMapper.insertSkuMasterSub(skuMasterSubOld);
            } else {
                skuMasterSubOld.setSkuRecommendFlag(skuMasterSub.getSkuRecommendFlag());
                skuMasterSubOld.setSkuSalesChannel(skuMasterSub.getSkuSalesChannel());
                skuMasterSubOld.setUpdateBy(operName);
                skuMasterSubOld.setUpdateTime(DateUtils.getNowDate());
                skuMasterSubMapper.updateSkuMasterSub(skuMasterSubOld);
            }

            // 计算单独某个产品指标得分
            skuMetricsScoreService.calculateSkuCodeMetricsScore(
                    skuMasterSub.getOwnerId(), skuMasterSub.getSkuCode());
        }
    }

    /**
     * 产品容量和关联SPU
     */
    private void importSkuProductMasterSubList(List<SkuMergeMasterSub> skuMergeMasterSubList,
                                               List<SkuProductMasterSub> skuProductMasterSubDataList,
                                               String operName) {
        // 更新 sku_merge_master_sub
        for (SkuMergeMasterSub skuMergeMasterSub : skuMergeMasterSubList) {

            // SKUM关联查询
            SkuMergeMasterSub skuMergeMasterSubOld = skuMergeMasterSubMapper.selectSkuMergeMasterSubBySkuCode(
                    skuMergeMasterSub.getOwnerId(), skuMergeMasterSub.getSkuCode());

            // 如果存在删除，再新增关联
            if (skuMergeMasterSubOld != null) {
                skuMergeMasterSubMapper.deleteSkuMergeMasterSubById(skuMergeMasterSubOld.getId());
            }
            skuMergeMasterSubOld = new SkuMergeMasterSub();
            skuMergeMasterSubOld.setOwnerId(skuMergeMasterSub.getOwnerId());
            skuMergeMasterSubOld.setSkuCode(skuMergeMasterSub.getSkuCode());
            skuMergeMasterSubOld.setSkuName(skuMergeMasterSub.getSkuName());
            skuMergeMasterSubOld.setSkumId(skuMergeMasterSub.getSkumId());
            skuMergeMasterSubOld.setSkumCode(skuMergeMasterSub.getSkumCode());
            skuMergeMasterSubOld.setCreateBy(operName);
            skuMergeMasterSubOld.setUpdateBy(operName);
            skuMergeMasterSubOld.setCreateTime(DateUtils.getNowDate());
            skuMergeMasterSubOld.setUpdateTime(DateUtils.getNowDate());
            skuMergeMasterSubMapper.insertSkuMergeMasterSub(skuMergeMasterSubOld);

            // SKUM 销售价格更新 前端已做控制处理
//            SkuMaster oldSkuMaster = skuMasterMapper.selectSkuMasterByGoodsCode(
//                    skuMergeMasterSub.getOwnerId(), skuMergeMasterSub.getSkuCode());
//            BigDecimal salePrice = oldSkuMaster.getSalePrice();
//            SkuMergeMaster skuMergeMaster = skuMergeMasterMapper.selectSkuMergeMasterBySkumCode(skuMergeMasterSub.getSkumCode());
//            skuMergeMaster.setSkumSalePrice(salePrice);
//            skuMergeMaster.setUpdateBy(operName);
//            skuMergeMaster.setUpdateTime(DateUtils.getNowDate());
//            skuMergeMasterMapper.updateSkuMergeMaster(skuMergeMaster);
        }

        // 更新  sku_product_master_sub
        for (SkuProductMasterSub skuProductMasterSub : skuProductMasterSubDataList) {

            SkuProductMasterSub skuProductMasterSubTmp = new SkuProductMasterSub();
            skuProductMasterSubTmp.setOwnerId(skuProductMasterSub.getOwnerId());
            skuProductMasterSubTmp.setSkumCode(skuProductMasterSub.getSkumCode());
            List<SkuProductMasterSub>  skuMergeMasterSubOldList = skuProductMasterSubMapper.selectSkuProductMasterSubList(skuProductMasterSubTmp);

            // 如果存在删除，再新增关联
            if (!skuMergeMasterSubOldList.isEmpty()) {
                skuProductMasterSubMapper.deleteSkuProductMasterSubById(skuMergeMasterSubOldList.get(0).getId());
            }
            SkuProductMasterSub skuMergeMasterSubOld = new SkuProductMasterSub();
            skuMergeMasterSubOld.setOwnerId(skuProductMasterSub.getOwnerId());
//            skuMergeMasterSubOld.setSpuId(skuProductMasterSub.getSpuId());
            skuMergeMasterSubOld.setSpuCode(skuProductMasterSub.getSpuCode());
            skuMergeMasterSubOld.setSkumId(skuProductMasterSub.getSkumId());
            skuMergeMasterSubOld.setSkumCode(skuProductMasterSub.getSkumCode());
            skuMergeMasterSubOld.setCreateBy(operName);
            skuMergeMasterSubOld.setUpdateBy(operName);
            skuMergeMasterSubOld.setCreateTime(DateUtils.getNowDate());
            skuMergeMasterSubOld.setUpdateTime(DateUtils.getNowDate());
            skuProductMasterSubMapper.insertSkuProductMasterSub(skuMergeMasterSubOld);

            SkuProductMaster skuProductMaster = new SkuProductMaster();
            skuProductMaster.setUpdateTime(DateUtils.getNowDate());
            skuProductMaster.setUpdateBy(operName);
            skuProductMasterMapper.updateSkuProductMaster(skuProductMaster);
        }

    }

    /**
     * 导入 关联SKUM
     */
    private void importSkuMergeMasterSubList(List<SkuMergeMasterSub> skuMergeMasterSubList, String operName) {

        for (SkuMergeMasterSub skuMergeMasterSub : skuMergeMasterSubList) {

            // SKUM关联查询
            SkuMergeMasterSub skuMergeMasterSubOld = skuMergeMasterSubMapper.selectSkuMergeMasterSubBySkuCode(
                    skuMergeMasterSub.getOwnerId(), skuMergeMasterSub.getSkuCode());

            // 如果存在删除，再新增关联
            if (skuMergeMasterSubOld != null) {
                skuMergeMasterSubMapper.deleteSkuMergeMasterSubById(skuMergeMasterSubOld.getId());
            }
            skuMergeMasterSubOld = new SkuMergeMasterSub();
            skuMergeMasterSubOld.setOwnerId(skuMergeMasterSub.getOwnerId());
            skuMergeMasterSubOld.setSkuCode(skuMergeMasterSub.getSkuCode());
            skuMergeMasterSubOld.setSkuName(skuMergeMasterSub.getSkuName());
            skuMergeMasterSubOld.setSkumId(skuMergeMasterSub.getSkumId());
            skuMergeMasterSubOld.setSkumCode(skuMergeMasterSub.getSkumCode());
            skuMergeMasterSubOld.setCreateBy(operName);
            skuMergeMasterSubOld.setUpdateBy(operName);
            skuMergeMasterSubOld.setCreateTime(DateUtils.getNowDate());
            skuMergeMasterSubOld.setUpdateTime(DateUtils.getNowDate());
            skuMergeMasterSubMapper.insertSkuMergeMasterSub(skuMergeMasterSubOld);

            // SKUM 销售价格更新 前端已做控制处理
            SkuMaster oldSkuMaster = skuMasterMapper.selectSkuMasterByGoodsCode(
                    skuMergeMasterSub.getOwnerId(), skuMergeMasterSub.getSkuCode());
            BigDecimal salePrice = oldSkuMaster.getSalePrice();
            SkuMergeMaster skuMergeMaster = skuMergeMasterMapper.selectSkuMergeMasterBySkumCode(skuMergeMasterSub.getSkumCode());
            skuMergeMaster.setSkumSalePrice(salePrice);
            skuMergeMaster.setUpdateBy(operName);
            skuMergeMaster.setUpdateTime(DateUtils.getNowDate());
            skuMergeMasterMapper.updateSkuMergeMaster(skuMergeMaster);
        }
    }

    @Async
    public void importSyncSkuToEs(List<SkuMasterSub> skuMasterSubList,
                                  List<SkuMergeMasterSub> skuMergeMasterSubList) {

        for (SkuMasterSub skuMasterSub : skuMasterSubList) {
            SkuMaster skuSelectMaster = new SkuMaster();
            skuSelectMaster.setId(skuMasterSub.getSkuId());
            List<SkuMaster> skuMasterList = skuMasterMapper.selectSkuMasterToEs(skuSelectMaster);
            if(!skuMasterList.isEmpty()){
                syncSkuToEs(skuMasterList, false);
            }
        }

        for (SkuMergeMasterSub skuMergeMasterSub : skuMergeMasterSubList) {
            SkuMergeMaster skuMergeMaster = skuMergeMasterMapper.selectSkuMergeMasterById(skuMergeMasterSub.getSkumId());
            if(null != skuMergeMaster){
                skuMergeMasterService.syncSkumToEs(skuMergeMaster);
            }

            // 此SKU编码 在 第一个sheet不存在时 也需要同步 20250325
            SkuMaster skuSelectMaster = new SkuMaster();
            skuSelectMaster.setId(skuMergeMasterSub.getSkuId());
            List<SkuMaster> skuMasterList = skuMasterMapper.selectSkuMasterToEs(skuSelectMaster);
            if(!skuMasterList.isEmpty()){
                syncSkuToEs(skuMasterList, false);
            }
        }
    }


    @Override
    public int skuPriceCompare() {
        log.info("enter skuPriceCompare");

        try {
            List<SkuPriceEntity> retList = skuMasterMapper.skuPriceCompare();
            for (SkuPriceEntity entity : retList){
                //log
                SkuSampleUpdateLog skuSampleUpdateLog = new SkuSampleUpdateLog();
                skuSampleUpdateLog.setOwnerId(entity.getOwnerId());
                skuSampleUpdateLog.setSkuCode(entity.getSkuCode());
                skuSampleUpdateLog.setSkuName(entity.getSkuName());
                skuSampleUpdateLog.setMtype(String.valueOf(SkuMasterConstants.SKU_SAMPLE_M_TYPE.PRODUCT_PRICE.getDesc()));
                skuSampleUpdateLog.setMmodule(String.valueOf(SkuMasterConstants.SKU_SAMPLE_M_MODULE.SYS_EX.getDesc()));
                skuSampleUpdateLog.setOldValue(entity.getOldSkuPirce().setScale(2, RoundingMode.HALF_UP).toString());
                skuSampleUpdateLog.setNewValue(entity.getNewSkuPirce().setScale(2, RoundingMode.HALF_UP).toString());
                skuSampleUpdateLog.setUpdateBy("system");
                skuSampleUpdateLog.setUpdateTime(DateUtils.getNowDate());
                skuSampleMapper.insertSkuSampleUpdateLog(skuSampleUpdateLog);
            }

        } catch (Exception e) {

            throw new RuntimeException(e);
        }

        return 0;
    }


    public static boolean isPositiveNumber(String param ) {
       double number = Double.parseDouble(param);
        try {
            // 判断是否大于0
            if (number < 0){
                return false;
            }
            else return true;
        } catch (NumberFormatException e) {
            // 转换失败，不是有效的数字
            return false;
        }
    }
}
